package com.wujilin.okra.fragment;

import static com.wujilin.okra.Okra.FORMATTER_DATE_TIME;
import static com.wujilin.okra.Okra.EXTRA_KEY_RESULT_CONTENT;
import static com.wujilin.okra.Okra.EXTRA_KEY_RESULT_GRADE;
import static com.wujilin.okra.Okra.EXTRA_KEY_RESULT_ID;
import static com.wujilin.okra.Okra.EXTRA_OBJECTIVE_ID;
import static com.wujilin.okra.Okra.F_CONTENT;
import static com.wujilin.okra.Okra.F_GRADE;
import static com.wujilin.okra.Okra.F_TIME;
import static com.wujilin.okra.Okra.T_KEY_RESULT;

import org.joda.time.DateTime;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;

import com.wujilin.okra.Okra;
import com.wujilin.okra.R;
import com.wujilin.okra.database.Sql;

public class KeyResultEditFragment extends KeyResultDialogFragment {
	private EditText contentEdit;
	private RatingBar gradeRating;
	
	public static KeyResultEditFragment newInstance(long id, String content, double grade, long objectiveId) {
		Bundle args = new Bundle();
		args.putLong(EXTRA_KEY_RESULT_ID, id);
		args.putLong(EXTRA_OBJECTIVE_ID, objectiveId);
		args.putString(EXTRA_KEY_RESULT_CONTENT, content);
		args.putDouble(Okra.EXTRA_KEY_RESULT_GRADE, grade);
		
		KeyResultEditFragment fragment = new KeyResultEditFragment();
		fragment.setArguments(args);
		
		return fragment;
	}

	@Override
	public void onClickPositiveButton(DialogInterface dialog, Bundle args) {
		long id = args.getLong(EXTRA_KEY_RESULT_ID, 0);
		String content = contentEdit.getText().toString();
		String time = DateTime.now().toString(FORMATTER_DATE_TIME);
		double grade = (gradeRating.getRating() * 2) / 10.0;
		Sql.update(T_KEY_RESULT, id, F_CONTENT, content, F_TIME, time, F_GRADE, grade);
	}

	@Override
	public void onCreateDialog(Builder builder) {
		View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_key_result_edit, null);
		View titleView = getActivity().getLayoutInflater().inflate(R.layout.dialog_key_result_title, null);
		contentEdit = (EditText) view.findViewById(R.id.key_result_content);
		gradeRating = (RatingBar) titleView.findViewById(R.id.grade);
		
		Bundle args = getArguments();
		String content = args.getString(EXTRA_KEY_RESULT_CONTENT);
		contentEdit = (EditText) view.findViewById(R.id.key_result_content);
		contentEdit.setText(content);
		contentEdit.setSelection(content.length());
		
		double grade = args.getDouble(EXTRA_KEY_RESULT_GRADE);
		gradeRating.setRating((float) (grade * 10 / 2));
		
		builder.setCustomTitle(titleView).setView(view);
	}
}
